﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IdentityModel.Policy;
using System.IdentityModel.Claims;
using WCFAuthorization.Service;

namespace WCFAuthorization.Server.Security
{
    public class CustomAuthorizationPolicy : IAuthorizationPolicy
    {
        string id = string.Empty;

        public CustomAuthorizationPolicy()
        {
            id = new Guid().ToString();
        }

        #region IAuthorizationPolicy Members

        public bool Evaluate(EvaluationContext Context, ref object ObjectContext)
        {
            bool r_object = false;

            if (ObjectContext == null)
            {
                ObjectContext = r_object;
            }
            else
            {
                r_object = Convert.ToBoolean(ObjectContext);
            }

            if (!r_object)
            {
                List<Claim> claims = new List<Claim>();
                foreach (ClaimSet cs in Context.ClaimSets)
                {
                    foreach (Claim claim in cs.FindClaims(ClaimTypes.Name, Rights.PossessProperty))
                    {
                        Console.WriteLine("用户 : {0}", claim.Resource);
                        foreach (string str in GetOperationList(claim.Resource.ToString()))
                        {
                            claims.Add(new Claim("net.tcp://espier.cc/HandRegister/", str, Rights.PossessProperty));
                            Console.WriteLine("授权的资源:{0}", str);
                        }
                    }
                }
                Context.AddClaimSet(this, new DefaultClaimSet(Issuer, claims));
            }
            return true;
        }

        private static IEnumerable<string> GetOperationList(string name)
        {
            List<string> rights = new List<string>();
            var query = Cacher.UsersCache
                .Where(p => p.UserName.Equals(name));
            if (query.Count() > 0)
            {
                User user = query.FirstOrDefault();
                if (user.Enable || user.ExpiredTime > DateTime.Now)
                {
                    //授权的资源
                    rights.Add(string.Format("net.tcp://espier.cc/HandRegister/GetValid"));
                    rights.Add(string.Format("net.tcp://espier.cc/HandRegister/Upload"));
                }

            }
            //公开资源
            rights.Add(string.Format("net.tcp://espier.cc/HandRegister/CheckUser"));
            return rights;
        }

        public System.IdentityModel.Claims.ClaimSet Issuer
        {
            get { return ClaimSet.System; }
        }

        #endregion

        #region IAuthorizationComponent Members

        public string Id
        {
            get { return id; }
        }

        #endregion
    }
}
